function NewCrudGrid(ServiceURL, ServiceParams, ParentWindowsId, ModelName)
{

	var svcURL = ServiceURL;
	var svcParams = ServiceParams;
	
	ServiceParams = ResetURLPageParamTo1(ServiceParams);
	AjaxCallStatus = GetObjects(ServiceURL+"?"+ServiceParams);
	AjaxCallStatus.then(function()
	{
		XMLresp = GetLastAJAXResponse();
		
		CreateCrudGrid(XMLresp, ParentWindowsId, svcURL, svcParams, ModelName);
	});
	AjaxCallStatus.fail(function()
	{
		CreateErrorWindow("Couldn't get records."
				+ " Check connection with server. " +
				"Cause: " + GetLastAJAXResponse());
	});
	
}
function UpdateCrudGrid(NewServicePath,NewServicePathParams, ParentWinID, GridID, ToolbarID, ModName)
{
	
	AjaxCallStatus = GetObjects(NewServicePath+"?"+NewServicePathParams);
	AjaxCallStatus.then(function()
	{
		XMLresp = GetLastAJAXResponse();
		$("#"+GridID).remove();
		$("#"+ToolbarID).remove();
		
		CreateCrudGrid(XMLresp, ParentWinID, NewServicePath,NewServicePathParams, ModName);
	});
	AjaxCallStatus.fail(function()
	{
		CreateErrorWindow("Couldn't get records."
				+ " Check connection with server. " +
				"Cause: " + GetLastAJAXResponse());
	});
	
	
}

function CreateCrudGrid(XMLresp, DivIdForAppend, ServiceURL, ServiceParams, ModName)
{
	var XMLresponse = XMLresp;
	
	//Hay que llevar los ID's del DOM creado Dinamicamente	
	//Y la url a la que le estamos pegando
	var ModelName = ModName;
	var ServicePath = ServiceURL;
	var ServiceParameters = ServiceParams;
	var WindowsID = DivIdForAppend;
	var GridID = WindowsID+"-Grid";
	var GridHeaderID = GridID+"-Header";
	var ToolbarID = WindowsID +"-Toolbar";
	var DeleteButtonID = WindowsID+"DeleteButton";
	var EditButtonID = WindowsID+"EditButton";
	var CreateButtonID = WindowsID+"CreateButton";
	var CopyButtonID = WindowsID+"CopyButton";
	var SearchButtonID = WindowsID+"SearchButton";
	var PreviousPageButtonID = WindowsID+"PreviousPageButton";
	var NextPageButtonID = WindowsID+"NextPageButton";
	
	var objectsCount = 0;
	var attrcount = 0;
	var GridSelectedObject = null;
	
	
	/*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*//*GRID*/
		
		
		
		$("#"+WindowsID).append("<table style='width:100%;' id='"+GridID+"' class='crudgrid ui-widget ui-widget-content' ></table>");//Empezamos a crear la tabla
			
		$('#'+GridID).selectable({
			  filter:'tbody tr'});
		
		//foreach object tag
		
		$('#'+ GridID).append("<thead id='"+GridHeaderID+"' class='ui-widget-header'></thead>" ); //un row para el header
		$(XMLresponse).find('object').each
		(function()
		{
			var RowID = GridID + "-row-"+objectsCount.toString();
						
			$('#'+ GridID).append("<tr id='"+RowID+"'></tr>" ); //un row por objeto
			
												
			var attrCount = 0;
			var CurrentObj = $(this);
								
								
			/***********************************************************/
			//Load all the atributes of the current object in the list,
			//and all its logic
			
			CurrentObj.find('atribute').each 
			(function()
			{
				CurrentAttribute = $(this);
												
				
				
				//ID unica para cada input, para agregarle un handler especifico onTextChange
				var FieldID = GridID + "-Field-"+objectsCount.toString()+"-"+attrCount.toString(); 
				
				
				$( "#"+RowID).unbind('click') //Esto es un workaround por un bug de Jquery
				$("#"+RowID).bind
				(
						'click',
						function(EventArgs)
						{
							var FunctionObj = CurrentObj;
							GridSelectedObject = FunctionObj;	//siempre queremos conocer el obj seleccionado								
						}
				
				);
								
				if(objectsCount == 0) //Depending wether is the first object or not, we make the header 
					$("#"+GridHeaderID).append("<th id='"+FieldID+"'>"+CurrentAttribute.attr('name')+"</th>");// Columna para el field
										
				$("#"+RowID).append("<td id='"+FieldID+"'><span id='"+FieldID+"'>"+CurrentAttribute.text()+"</span></td>");// Columna para el field
				
				
				
				if (CurrentAttribute.attr('isprimitive') == 'false') //If the object attribute isnot a primitive we must make a link, because is a child object
				{
					var CurrentObjectClass = CurrentObj.find('class').text();
					var CurrentObjectID = CurrentObj.find('atribute[name=id]').text();
					var CurrentChildObjectClass;
					if (CurrentAttribute.attr("generictype") != "none")
						CurrentChildObjectClass	= CurrentAttribute.attr("generictype");
					else
						CurrentChildObjectClass = CurrentAttribute.attr("type");
					
					var CurrentParentChildAttributeName = CurrentAttribute.text();
					
					//$('#'+FieldID).append('<button id="'+FieldID+'-Button"></button>');
					$("span[id="+FieldID+"]").addClass("GridNonPrimitive");
					$("span[id="+FieldID+"]").bind
					(
						'click',
						function(EventArgs)
						{
							//We must know the coordinates in which the click took place, to create the context menu
							var MousePositionX = EventArgs.pageX;
							var MousePositionY = EventArgs.pageY;
							
							
							var ObjectClass = CurrentObjectClass;
							var ObjectID = CurrentObjectID;
							var ChildObjectClass = CurrentChildObjectClass;
							var ParentChildAttributeName = CurrentParentChildAttributeName;
							
							var SvcPath = "svc/search";							
							var SvcParams = "model="+ChildObjectClass+"&Page=1&ParentChildAttribute="+ParentChildAttributeName+"&ParentModel="+ObjectClass+"&ParentModelID="+ObjectID;
							
							CreateChildRelationContextMenu(MousePositionX, MousePositionY, SvcPath, SvcParams, ChildObjectClass);
							//NewCrudWindow(SvcPath,SvcParams,ChildObjectClass);
							
						}
					);
				}
			
				attrCount++;
			}		
			);
			

		
			objectsCount++;
		}		
		);
		
		if (objectsCount == 0) 
			$('#'+GridID).append("<tr><td><div class='ui-state-highlight ui-corner-all'><p><span style='float: left; margin-right: .3em;' class='ui-icon ui-icon-info'></span>There aren't items to show!</p></div></td></tr>");
		/*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*//*TOOLBAR*/
		
		$("#"+WindowsID).append(
				"<div id='"+ToolbarID+"'>"
					+"<div id='CrudButtons'>"
						+"<button id='"+CreateButtonID+"' title='New...' ></button>"
						+"<button id='"+EditButtonID+"' title='Edit...'></button>"
						+"<button id='"+DeleteButtonID+"' title='Delete...'></button>"
						+"<button id='"+SearchButtonID+"' title='Search...'></button>"
						+"<button id='"+CopyButtonID+"' title ='Copy... (To assign to another model)'></button>"
					+"</div>"
					+"<div id='PagingButtons'>"
						+"<button id='"+PreviousPageButtonID+"' title='Previous Records...'></button>"
						+"<button id='"+NextPageButtonID+"' title='Next Records...'></button>"
					+"</div>"
				+"</div>"
			);
				
		
		$( "#"+CreateButtonID ).button({text: false, icons: {primary: "ui-icon-plusthick" }}
		).click(function()
		{
			var CreateWindowsResult = NewCreateModelWindow(ServiceParams,ModelName);	
			if (CreateWindowsResult != null && CreateWindowsResult != undefined)
			{
				CreateWindowsResult.then(function (ModalWindowResult) 
				{
					UpdateCrudGrid(ServicePath, ServiceParameters, GridID, ToolbarID, ModelName);
				});
			}
			}
		
		);
		
		
		$( "#"+SearchButtonID ).button({text: false, icons: {primary: "ui-icon-search" }}
		).click(function()
		{
			NewSearchWindow(ServicePath,ServiceParameters,ModelName);
		}
		);
		
		
		$( "#"+DeleteButtonID ).button({text: false, icons: {primary: "ui-icon-trash" }}
		).click(function()
				{
				 	if (GridSelectedObject != null)
				 		{
							SerializedObject = GridSelectedObject.prop('outerHTML');
						 	
					 		//We delete the object only on confirm	
						 	var ConfirmWindowResult = CreateConfirmWindow();
						 	//On confirm true;
						 	ConfirmWindowResult.then(function (ModalWindowResult) 
						 	{
			                    //We update the windows only if the AJAX request to delete is successful
						 		var AjaxRequestResult = DeleteObject(SerializedObject)
						 		AjaxRequestResult.then(function(AjaxRequestResult)
			                    {
			                    	UpdateCrudGrid(ServicePath, ServiceParameters, WindowsID, GridID, ToolbarID, ModelName);
			                    });
			                    
								
			                });
				 		}
				});
		
		$( "#"+EditButtonID ).button({text: false, icons: {primary: "ui-icon-pencil" }}
		).click(function()
				{
					if (GridSelectedObject != null)
			 		{	
							SerializedObject = GridSelectedObject.prop('outerHTML');
							SerializedObject = "<objects> /n"+ SerializedObject + "/n </objects>";
													
							var EditWindowResult = NewEditModelWindow(SerializedObject);
							EditWindowResult.then(function (modalWindowResult) 
						 	{
								UpdateCrudGrid(ServicePath, ServiceParameters, WindowsID, GridID, ToolbarID, ModelName);
							});
			 		}
				});

		$( "#"+CopyButtonID ).button({text: false, icons: {primary: "ui-icon-pin-s" }}
		).click(function()
		{
			SerializedObject = GridSelectedObject.prop('outerHTML');
			SerializedObject = "<objects> /n"+ SerializedObject + "/n </objects>";
			
			CopyModelToClipboard(SerializedObject);
		});
		
		
		
		$( "#"+PreviousPageButtonID ).button({text: false, icons: {primary: "ui-icon-arrowthick-1-w" }}
		).click(function()
				{
					ServiceParameters = DecrementURLPageParam(ServiceParameters);
					UpdateCrudGrid(ServicePath, ServiceParameters, WindowsID, GridID, ToolbarID, ModelName);
				});
		
		$( "#"+NextPageButtonID ).button({text: false, icons: {primary: "ui-icon-arrowthick-1-e" }}
		).click(function()
				{
					ServiceParameters = IncrementURLPageParam(ServiceParameters);
					UpdateCrudGrid(ServicePath, ServiceParameters,  WindowsID, GridID, ToolbarID, ModelName);
				
				});
		
		
}